// 登录与权限管理控制器
const jwt = require('jsonwebtoken');
const User = require('../models/user.model');
const Role = require('../models/role.model');
const Menu = require('../models/menu.model');
const { Op } = require('sequelize');
const { jwtSecret } = require('../utils/jwtUtils');
const bcrypt = require('bcryptjs');
const sendResponse = require('../utils/response');
const buildMenuTree = require('../utils/menuTree');

// 登录
exports.login = async (req, res, next) => {
  const { username, password } = req.body;

  try{
    const user = await User.findOne({
      where: {
        username: username
      }
    });
  
    if ( !user || !bcrypt.compareSync(password, user.password) ) {
      return sendResponse(res ,{ code: 401, message: '用户名或密码错误' });
    }
  
    // 生成 token
    const token = jwt.sign({ id: user.id, username: user.username }, jwtSecret, { expiresIn: '1h' });
    sendResponse(res, { message: '登录成功', data: token });
  } catch (error) {
    next(error);
  }
};

// 退出登录
exports.logout = (req, res, next) => {
  sendResponse(res, { message: '退出登录成功' });
};

// 获取用户信息
exports.info = async (req, res, next) => {
  // 获取用户 ID
  const { username } = req.user;

  try {
    // 获取用户信息
    const user = await User.findOne({
      where: {
        username: username
      },
      as: 'Users',
      attributes: ['id', 'username', 'name', 'avatar'],
      include: [{ 
        model: Role,
        as: 'Roles',
        attributes: ['id', 'roleName', 'remark'],
        through: { attributes: [] }, // 如果不想要中间表的属性
        include: [{
          model: Menu,
          as: 'Menus', // 使用 Role-Menu 关联定义的别名
          where: { level: { [Op.or]: [1,2,3] } }, // level不等于4
          attributes: ['id', 'name', 'pid', 'code', 'level'],
          through: { attributes: [] }, // 如果不想要中间表的属性
          // include: [{
          //   model: Menu,
          //   as: 'children', // 使用自关联别名
          //   where: { level: 4 },
          //   required: false,
          // }]
        }]
      }]
    });

    console.log("---获取用户信息---");

    // 直接提取按钮并去重
    // const buttons = user.Roles
    //   .flatMap(role => role.Menus)
    //   .flatMap(menu => menu.children || []) // 防止undefined
    //   .filter((button, index, self) =>
    //     self.findIndex(b => b.id === button.id) === index
    //   );
    // 提取按钮的 code
    // const btnCodeArray = buttons.map(item => item.code);
    
    // TODO 延长token登录时间
    // 获取token
    // 
    // 返回用户信息
    sendResponse(res, { 
      message: '获取用户信息成功', 
      data: {
        routes: req.user.menus,
        buttons: req.user.buttons,
        roles: user.Roles,
        name: user.name,
        avatar: user.avatar
      }
    });
  } catch (error) {
    next(error);
  }
};

// 获取用户权限
exports.getMenu = async (req, res, next) => {
  const { username } = req.user;
  try {
    const user = await User.findOne({
      where: {
        username: username
      }
    });
    sendResponse(res, { message: '获取用户权限成功', data: user.rolename });
  } catch (error) {
    next(error);
  }
};